const express = require('express');
let router = express.Router();

//日志
const {
    logger
} = require('../../config/logger');

const Response = require('../../utils/response')

//引入数据库连接池
const pool = require('../../config/mysql');
//引入数据库语句
const query = require('../../db/noticeQuery/noticeQuery');

//解析token
const {
    token_sign,
    token_verify
} = require('../../config/jwt')

//引入时间模块
const sd = require('silly-datetime');

//解析from
const multiparty = require('multiparty');
//存储文件 
const path = require('path');
const fs = require('fs');

//获取公告列表(默认降序)
router.get('/noticeList', function (req, res) {
    const count = req.query.count ? parseInt(req.query.count) : 10;
    const page = req.query.page ? parseInt((req.query.page)) - 1 : 0;
    pool.query(query.select_notice_admin, [count, page], (error, result) => {
        if (error) {
            res.json(Response.error("获取公告列表失败", null));
            logger().error("获取公告列表失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取公告列表成功", data));
        }
    });
})

//获取公告列表(升序)
router.get('/noticeListByAsc', function (req, res) {
    const count = req.query.count ? parseInt(req.query.count) : 10;
    const page = req.query.page ? parseInt((req.query.page)) - 1 : 0;
    pool.query(query.select_notice_admin_asc, [count, page], (error, result) => {
        if (error) {
            res.json(Response.error("获取公告列表(升序)失败", null));
            logger().error("获取公告列表(升序)失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取公告列表(升序)成功", data));
        }
    });
})

//模糊搜索公告标题
router.get('/searchNotice_title', function (req, res) {
    const keywords = req.query.keywords;
    pool.query(query.select_notice_admin_title, keywords, (error, result) => {
        if (error) {
            res.json(Response.error("获取公告模糊搜索发表者列表失败", null));
            logger().error("获取公告模糊搜索发表者列表失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取公告模糊搜索发表者列表成功", data));
        }
    });
})

//模糊搜索公告详细
router.get('/searchNotice_describe', function (req, res) {
    const keywords = req.query.keywords;
    pool.query(query.select_notice_admin_describe, keywords, (error, result) => {
        if (error) {
            res.json(Response.error("获取公告搜索公告详细列表失败", null));
            logger().error("获取公告搜索公告详细列表失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取公告搜索公告详细列表成功", data));
        }
    });
})

//状态筛选
router.get('/searchNotice_status', function (req, res) {
    const status = req.query.status;
    const count = req.query.count ? parseInt(req.query.count) : 10;
    const page = req.query.page ? parseInt((req.query.page)) - 1 : 0;
    pool.query(query.select_status_admin, [status, count, page], (error, result) => {
        if (error) {
            res.json(Response.error("获取公告状态筛选列表失败", null));
            logger().error("获取公告状态筛选列表失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取公告状态筛选列表成功", data));
        }
    });
})

//修改公告状态
router.post('/changeStatus', function (req, res) {
    const noticeId = req.body.noticeId;
    const noticeStatus = req.body.noticeStatus;
    pool.query(query.change_notice_admin, [noticeStatus, noticeId], (error, result) => {
        if (error) {
            res.json(Response.error("修改公告状态失败", null));
            logger().error("修改公告状态失败: " + error);
        } else {
            res.json(Response.success("修改公告状态成功", null));
        }
    });
})

//添加公告
router.post('/addNotice', function (req, res) {
    const ht = req.protocol; // 获取协议（http或者https）
    const host = req.headers.host; // 获取域名和端口号
    let form = new multiparty.Form({
        uploadDir: path.join(__dirname, '../../../public/images/notice')
    }) // 设置文件存储路径
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    form.parse(req, (err, msg, files) => {
        try {
            const noticeTitle = msg['noticeTitle'][0];
            const noticeDescribe = msg['noticeDescribe'][0];
            const noticeTop = msg['noticeTop'][0];
            const image = files['image'][0];
            const newPath = form.uploadDir + "/" + image.originalFilename;
            fs.renameSync(image.path, newPath)
            const url = ht + "://" + host + "/images/notice/" + image.originalFilename;
            pool.query(query.insert_notive_admin, [noticeTitle, noticeDescribe, url, noticeTop, time], (error, result) => {
                if (error) {
                    logger().error("添加公告失败: " + error);
                    res.json(Response.error("添加公告失败", null));
                } else {
                    res.json(Response.success("添加公告成功", null));
                }
            });
        } catch (error) {
            res.json(Response.error("添加公告失败", null));
            logger().error("添加公告失败: " + error);
        }
    })
})

//修改显示层级
router.post('/changeIndex', function (req, res) {
    const noticeId = req.body.noticeId;
    const noticeIndex = req.body.noticeIndex;
    pool.query(query.select_notice_admin_index, noticeIndex, (error, result) => {
        if (error) {
            res.json(Response.error("修改显示层级失败", null));
            logger().error("修改显示层级失败: " + error);
        } else {
            const {
                count
            } = JSON.parse(JSON.stringify(result[0]));
            if (count !== 0) {
                res.json(Response.error("修改显示层级失败: 存在相同的层级!", null));
            } else {
                pool.query(query.change_notice_admin_index, [noticeIndex, noticeId], (error, result) => {
                    if (error) {
                        res.json(Response.error("修改显示层级失败", null));
                        logger().error("修改显示层级失败: " + error);
                    } else {
                        res.json(Response.success("修改显示层级成功", null));
                    }
                });
            }
        }
    });

})

//删除公告
router.post('/deleteNotice', function (req, res) {
    const noticeId = req.body.noticeId;
    pool.query(query.delete_notice, noticeId, (error, result) => {
        if (error) {
            res.json(Response.error("删除公告消息错误", null));
            logger().error(`删除公告消息错误: ${error}`);
            return;
        } else {
            res.json(Response.success("删除公告成功", null));
        }
    });
})


module.exports = router;